package com.ruoyi.am.controller;

import java.util.*;

import com.ruoyi.am.domain.AmRosterLog;
import com.ruoyi.am.service.IAmRosterLogService;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.am.domain.AmRoster;
import com.ruoyi.am.service.IAmRosterService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 排班管理Controller
 * 
 * @author hkkk
 * @date 2020-12-04
 */
@Controller
@Service
@RequestMapping("/am/roster")
public class AmRosterController extends BaseController
{
    private String prefix = "am/roster";

    private final static Map<Long, AmRoster> users = new LinkedHashMap<Long, AmRoster>();
    {
    }

    @Autowired
    private IAmRosterService amRosterService;
    @Autowired
    private IAmRosterLogService amRosterLogService;

    @RequiresPermissions("am:roster:view")
    @GetMapping()
    public String roster()
    {
        return prefix + "/roster";
    }

    /**
     * 查询排班管理列表
     */
    @RequiresPermissions("am:roster:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(AmRoster amRoster)
    {
        Date date=new Date();
        startPage();
        List<AmRoster> list1=amRosterService.selectAmRosterByMonth(5);
        return getDataTable(list1);
    }

    /**
     * 导出排班管理列表
     */
    @RequiresPermissions("am:roster:export")
    @Log(title = "排班管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(AmRoster amRoster)
    {
        List<AmRoster> list = amRosterService.selectAmRosterList(amRoster);
        ExcelUtil<AmRoster> util = new ExcelUtil<AmRoster>(AmRoster.class);
        return util.exportExcel(list, "roster");
    }

    /**
     * 新增排班管理
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存排班管理
     */
    @RequiresPermissions("am:roster:add")
    @Log(title = "排班管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(AmRoster amRoster)
    {
        return toAjax(amRosterService.insertAmRoster(amRoster));
    }

    /**
     * 修改排班管理
     */
    @GetMapping("/edit/{rosterId}")
    public String edit(@PathVariable("rosterId") Long rosterId, ModelMap mmap)
    {
        AmRoster amRoster = amRosterService.selectAmRosterById(rosterId);
        mmap.put("amRoster", amRoster);
        return prefix + "/edit";
    }

    /**
     * 修改保存排班管理
     */
    @RequiresPermissions("am:roster:edit")
    @Log(title = "排班管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(AmRoster amRoster)
    {
        return toAjax(amRosterService.updateAmRoster(amRoster));
    }

    /**
     * 删除排班管理
     */
    @RequiresPermissions("am:roster:remove")
    @Log(title = "排班管理", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(amRosterService.deleteAmRosterByIds(ids));
    }

    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<AmRoster> util = new ExcelUtil<AmRoster>(AmRoster.class);
        List<AmRoster> userList = util.importExcel(file.getInputStream());
        try {
            amRosterService.deleteAmRosterByMonth(Long.parseLong(userList.get(0).getMonth()));
        }
        catch (NumberFormatException e){
            return AjaxResult.error("月份格式错误请检查");
        }
        String message = importUser(userList, updateSupport);
        return AjaxResult.success(message);
    }

    public String importUser(List<AmRoster> userList, Boolean isUpdateSupport)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new BusinessException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (AmRoster user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                boolean userFlag = false;
                if(amRosterService.selectAmRosterByNameAndMonth(user.getName(),user.getMonth())!=null){
                    userFlag = true;
                    break;
                }
                if (!userFlag)
                {
                    amRosterService.insertAmRoster(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、用户 " + user.getName() + " 导入成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、用户 " + user.getName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<AmRoster> util = new ExcelUtil<AmRoster>(AmRoster.class);
        return util.importTemplateExcel("排班数据");
    }

    @GetMapping("/getRoster")
    @ResponseBody
    public AjaxResult getRoster(){
        Date date=new Date();
        List<AmRoster> list1=amRosterService.selectAmRosterByMonth(date.getMonth()+1);
        return AjaxResult.success(list1);
    }

    @PostMapping("/exchange")
    @ResponseBody
    @Transactional
    public AjaxResult exchange(@RequestParam String json_data){
        try {

            String[] data = json_data.split("\\,");

            String fromName = data[0];
            String toName = data[1];
            int fromDate = Integer.parseInt(data[2]);
            int toDate = Integer.parseInt(data[3]);
            int driver_id = Integer.parseInt(data[4]);

            String toOrder, fromOrder;


            AmRoster fromRoster = amRosterService.selectAmRosterByNameAndMonth(fromName, new Date().getMonth() + 1+"");
            AmRoster toRoster = amRosterService.selectAmRosterByNameAndMonth(toName, new Date().getMonth() + 1+"");

            toOrder = getDs(toRoster, toDate);
            fromOrder = getDs(fromRoster, fromDate);


            toRoster = setDs(toRoster, toDate, fromOrder);
            fromRoster = setDs(fromRoster, fromDate, toOrder);

            amRosterService.updateAmRoster(toRoster);
            amRosterService.updateAmRoster(fromRoster);

            AmRosterLog amRosterLog = new AmRosterLog();
            amRosterLog.setFromName(fromRoster.getName());
            amRosterLog.setToName(toRoster.getName());
            amRosterLog.setFromDate((new Date().getMonth() + 1) + "月" + fromDate + "日");
            amRosterLog.setTodate((new Date().getMonth() + 1) + "月" + toDate + "日");
            amRosterLog.setFromId((long) driver_id);
            amRosterLogService.insertAmRosterLog(amRosterLog);

            return AjaxResult.success();
        }
        catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    @PostMapping("/getOneOrder")
    @ResponseBody
    public String getOneOrder(@RequestParam String name,int day){
        AmRoster amRoster = amRosterService.selectAmRosterByNameAndMonth(name, new Date().getMonth() + 1+"");
        if (amRoster==null)
            return "399";
        return getDs(amRoster,day);
    }

    public AmRoster setDs(AmRoster amRoster,int day,String order){
        switch (day){
            case 1:amRoster.setD1(order);break;
            case 2:amRoster.setD2(order);break;
            case 3:amRoster.setD3(order);break;
            case 4:amRoster.setD4(order);break;
            case 5:amRoster.setD5(order);break;
            case 6:amRoster.setD6(order);break;
            case 7:amRoster.setD7(order);break;
            case 8:amRoster.setD8(order);break;
            case 9:amRoster.setD9(order);break;
            case 10:amRoster.setD10(order);break;
            case 11:amRoster.setD11(order);break;
            case 12:amRoster.setD12(order);break;
            case 13:amRoster.setD13(order);break;
            case 14:amRoster.setD14(order);break;
            case 15:amRoster.setD15(order);break;
            case 16:amRoster.setD16(order);break;
            case 17:amRoster.setD17(order);break;
            case 18:amRoster.setD18(order);break;
            case 19:amRoster.setD19(order);break;
            case 20:amRoster.setD20(order);break;
            case 21:amRoster.setD21(order);break;
            case 22:amRoster.setD22(order);break;
            case 23:amRoster.setD23(order);break;
            case 24:amRoster.setD24(order);break;
            case 25:amRoster.setD25(order);break;
            case 26:amRoster.setD26(order);break;
            case 27:amRoster.setD27(order);break;
            case 28:amRoster.setD28(order);break;
            case 29:amRoster.setD29(order);break;
            case 30:amRoster.setD30(order);break;
            case 31:amRoster.setD31(order);break;
        }
        return amRoster;
    }
    
    
    public String getDs(AmRoster amRoster,int day){
        String order="";
        switch (day){
            case 1:order=amRoster.getD1();break;
            case 2:order=amRoster.getD2();break;
            case 3:order=amRoster.getD3();break;
            case 4:order=amRoster.getD4();break;
            case 5:order=amRoster.getD5();break;
            case 6:order=amRoster.getD6();break;
            case 7:order=amRoster.getD7();break;
            case 8:order=amRoster.getD8();break;
            case 9:order=amRoster.getD9();break;
            case 10:order=amRoster.getD10();break;
            case 11:order=amRoster.getD11();break;
            case 12:order=amRoster.getD12();break;
            case 13:order=amRoster.getD13();break;
            case 14:order=amRoster.getD14();break;
            case 15:order=amRoster.getD15();break;
            case 16:order=amRoster.getD16();break;
            case 17:order=amRoster.getD17();break;
            case 18:order=amRoster.getD18();break;
            case 19:order=amRoster.getD19();break;
            case 20:order=amRoster.getD20();break;
            case 21:order=amRoster.getD21();break;
            case 22:order=amRoster.getD22();break;
            case 23:order=amRoster.getD23();break;
            case 24:order=amRoster.getD24();break;
            case 25:order=amRoster.getD25();break;
            case 26:order=amRoster.getD26();break;
            case 27:order=amRoster.getD27();break;
            case 28:order=amRoster.getD28();break;
            case 29:order=amRoster.getD29();break;
            case 30:order=amRoster.getD30();break;
            case 31:order=amRoster.getD31();break;
        }
        return order;
    }

}
